package bylw.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import bylw.entity.Drug;
import bylw.entity.Url;

public class DrugHttpClient {
	private Drug drug = null;
	private HttpClient httpClient = new DefaultHttpClient();
	private HttpGet httpGet = null;
	private HttpResponse response = null;
	private HttpEntity entity = null;
	private JSONObject jsonObject = null;

	/*
	 * 用name替换urlList中的${name}，从网络中取得数据放到List<Drug>中
	 */
	public void getDrugList(String name, List<Url> urlList,
			List<Drug> drugList) {
		System.out.println("~~~");
		String urlPath = null;
		Drug newDrug = null;
		// 迭代取得数据
		for (Url url : urlList) {
			urlPath = url.getUrl().replace("{name}", name);
			newDrug = packagingIntoDrug(urlPath);
			if (newDrug != null) {
				drugList.add(newDrug);
			}
		}
	}

	/*
	 * 从网络中取得数据并封转成为Drug
	 */
	public Drug packagingIntoDrug(String urlPath) {
		try {
			// 使用HttpClient提交请求并取得数据，数据放到json中
			httpClient = new DefaultHttpClient();
			httpGet = new HttpGet(urlPath);
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						instream));
				String json = "";
				String line = "";
				while ((line = br.readLine()) != null) {
					json += line;
				}
				
				// 将操作json格式并把数据封转成Drug
				jsonObject = JSONObject.fromObject(json);
				drug = new Drug();
				drug.setId(jsonObject.getInt("id"));
				drug.setName(jsonObject.getString("name"));
				drug.setDescription(jsonObject.getString("description"));
				return drug;
			}

		} catch (Exception e) {
			// 视而无睹
			e.printStackTrace();
		}

		return null;
	}

}
